package in.hooray.shop.service;

import java.util.Map;

import javax.annotation.PostConstruct;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import me.hao0.alipay.core.Alipay;
import me.hao0.alipay.core.AlipayBuilder;
import me.hao0.alipay.model.pay.WapPayDetail;
import me.hao0.alipay.model.pay.WebPayDetail;
import me.hao0.alipay.model.refund.RefundDetail;

@Service
public class AlipayService {
	
	private final static Logger log = LoggerFactory.getLogger(AlipayService.class.getName());

	@Value("${pay.merchantId}")
    private String merchantId;

    @Value("${pay.secret}")
    private String secret;

    @Value("${pay.payNotifyUrl}")
    private String payNotifyUrl;

    @Value("${pay.refundNotifyUrl}")
    private String refundNotifyUrl;

    @Value("${pay.webReturnUrl}")
    private String webReturnUrl;

    @Value("${pay.wapReturnUrl}")
    private String wapReturnUrl;

    private Alipay alipay;
    
    @PostConstruct
    public void initAlipay(){
        alipay = AlipayBuilder
                    .newBuilder(merchantId, secret)
                    .build();
        log.debug(alipay.toString()); 
    }
    
    /**
     * web支付
     */
    public String webPay(WebPayDetail detail){
        detail.setNotifyUrl(payNotifyUrl);
        detail.setReturnUrl(webReturnUrl);
        return alipay.pay().webPay(detail);
    }

    /**
     * wap支付
     */
    public String wapPay(WapPayDetail detail) {
        detail.setNotifyUrl(payNotifyUrl);
        detail.setReturnUrl(wapReturnUrl);
        return alipay.pay().wapPay(detail);
    }

    /**
     * MD5验证
     */
    public Boolean notifyVerifyMd5(Map<String, String> params){
        return alipay.verify().md5(params);
    }

    /**
     * 退款申请
     */
    public Boolean refund(RefundDetail detail){
        detail.setNotifyUrl(refundNotifyUrl);
        return alipay.refund().refund(detail);
    }
    
}
